﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：庄金冬 
    //
    // 文件名：DAL_Helper.cs
    // 文件功能描述：数据格式转换类（将数据转为实体）
    // 创建标识：周司徒2009-03-09
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
    // 审核时间：
    // 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections.Generic;

using System.Text;
using HZ.DrugTrade.Model;
using System.Data;
using HZ.DrugTrade.Model.Enum;
using System.Reflection;
using System.Data.SqlClient;
namespace HZ.DrugTrade.DAL2
{
    /// <summary>
    /// 数据格式转换类（将数据转为实体）
    /// </summary>
    public class DAL_Helper
    {
        #region 字段

        private static IDictionary<string, IList<string>> _PKCache = null;
        /// <summary>
        /// 尾巴(防止一个类叫同名)
        /// </summary>
        const string TAIL = "_Tail";
        #endregion

        #region 属性
        /// <summary>
        /// 主键字典缓存
        /// </summary>
        public static IDictionary<string, IList<string>> PKCache
        {
            get
            {
                if (_PKCache == null)
                {
                    //构造缓存
                    RefreshPKCache();
                }
                return _PKCache;
            }
        }

        #endregion

        #region KeyOperationLog
        /// <summary>
        /// 根据DataRow获得KeyOperationLog对象
        /// </summary>
        /// <param name="dr">DataRow</param>
        /// <returns></returns>
        public static KeyOperationLog GetKeyOperationLogFromDataRow(DataRow dr)
        {
            KeyOperationLog log = new KeyOperationLog();
            log.OperationLogSerialID = dr["OperationLogSerialID"].ToString().Trim();
            log.Operator = dr["Operator"].ToString().Trim();
            log.OperateMessage = dr["OperateMessage"].ToString().Trim();
            log.OperateTime = new HZ.Common.ConvertHelper(dr["OperateTime"]).ToDateTime ?? DateTime.Now;
            log.OrgID = dr["OrgID"].ToString().Trim();
            log.ClientIP = dr["ClientIP"].ToString().Trim();//记录日志操作的IP add by zdc 
            return log;
        }

        /// <summary>
        /// 根据DataTable获得KeyOperationLog对象集合
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static IList<KeyOperationLog> GetKeyOperationLogsFromDataTable(DataTable dt)
        {
            IList<KeyOperationLog> logs = new List<KeyOperationLog>(dt.Rows.Count);
            foreach (DataRow dr in dt.Rows)
            {
                logs.Add(GetKeyOperationLogFromDataRow(dr));
            }
            return logs;
        }
        #endregion

        #region User
        /// <summary>
        /// 根据DataRow获得User对象
        /// </summary>
        /// <param name="dr">DataRow</param>
        /// <returns></returns>
        public static User GetUserFromDataRow(DataRow dr)
        {
            User user = new User();
            user.UserID = dr["UserID"].ToString().Trim();
            user.UserName = dr["UserName"].ToString().Trim();
            user.UserPassword = dr["UserPassword"].ToString().Trim();
            user.IsAdmin = new HZ.Common.ConvertHelper(dr["IsAdmin"]).ToBool ?? false;
            user.IsUsing = new HZ.Common.ConvertHelper(dr["IsUsing"]).ToBool ?? false;
            user.LastLoginTime = new HZ.Common.ConvertHelper(dr["LastLoginTime"]).ToDateTime ?? DateTime.Now;
            user.IsOnline = new HZ.Common.ConvertHelper(dr["IsOnline"]).ToBool ?? false;
            return user;
        }

        /// <summary>
        /// 根据DataTable获得User对象集合
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static IList<User> GetUsersFromDataTable(DataTable dt)
        {
            IList<User> users = new List<User>(dt.Rows.Count);
            foreach (DataRow dr in dt.Rows)
            {
                users.Add(GetUserFromDataRow(dr));
            }
            return users;
        }
        #endregion

        #region OperatingRule
        /// <summary>
        /// 根据DataRow获得OperatingRule对象
        /// </summary>
        /// <param name="dr">DataRow</param>
        /// <returns></returns>
        public static OperatingRule GetOperatingRuleFromDataRow(DataRow dr)
        {
            OperatingRule operatingRule = new OperatingRule();
            operatingRule.OperatingRuleID = dr["OperatingRuleID"].ToString().Trim();
            operatingRule.OperatingRuleName = dr["OperatingRuleName"].ToString().Trim();
            operatingRule.Module = EnumParse.GetModule(dr["Module"].ToString().Trim());
            operatingRule.HosFlag = new HZ.Common.ConvertHelper(dr["HosFlag"]).ToBool ?? false;
            operatingRule.ComFlag = new HZ.Common.ConvertHelper(dr["ComFlag"]).ToBool ?? false;
            operatingRule.CenFlag = new HZ.Common.ConvertHelper(dr["CenFlag"]).ToBool ?? false;

            return operatingRule;
        }

        /// <summary>
        /// 根据DataTable获得OperatingRule对象集合
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static IList<OperatingRule> GetOperatingRulesFromDataTable(DataTable dt)
        {
            IList<OperatingRule> operatingRules = new List<OperatingRule>(dt.Rows.Count);
            foreach (DataRow dr in dt.Rows)
            {
                operatingRules.Add(GetOperatingRuleFromDataRow(dr));
            }
            return operatingRules;
        }
        #endregion

        #region Role
        /// <summary>
        /// 根据DataRow获得Role对象
        /// </summary>
        /// <param name="dr">DataRow</param>
        /// <returns></returns>
        public static Role GetRoleFromDataRow(DataRow dr)
        {
            Role role = new Role();
            role.RoleID = dr["RoleID"].ToString().Trim();
            role.RoleName = dr["RoleName"].ToString().Trim();
            role.IsDefault = new HZ.Common.ConvertHelper(dr["IsDefault"]).ToBool ?? false;
            return role;
        }

        /// <summary>
        /// 构造Role对象
        /// </summary>
        /// <param name="role">角色记录</param>
        /// <param name="operatingRuleList">权限列表</param>
        /// <returns></returns>
        public static Role GetRoleFromDataRow(DataTable role, DataTable operatingRuleList)
        {
            Role role1 = new Role();
            DataRow dr = role.Rows[0];
            role1.RoleID = dr["RoleID"].ToString().Trim();
            role1.RoleName = dr["RoleName"].ToString().Trim();
            role1.IsDefault = new HZ.Common.ConvertHelper(dr["IsDefault"]).ToBool ?? false;
            IList<OperatingRule> list = GetOperatingRulesFromDataTable(operatingRuleList);

            role1.OperatingRuleList = (List<OperatingRule>)list;

            return role1;
        }

        /// <summary>
        /// 根据DataTable获得Role对象集合
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static IList<Role> GetRolesFromDataTable(DataTable dt)
        {
            IList<Role> roles = new List<Role>(dt.Rows.Count);
            foreach (DataRow dr in dt.Rows)
            {
                roles.Add(GetRoleFromDataRow(dr));
            }
            return roles;
        }
        #endregion

        #region Org
        /// <summary>
        /// 根据DataRow获得Org对象
        /// </summary>
        /// <param name="dr">DataRow</param>
        /// <returns></returns>
        public static Org GetOrgFromDataRow(DataRow dr)
        {
            Org org = new Org();
            org.OrgID = dr["OrgID"].ToString().Trim();
            org.OrgName = dr["OrgName"].ToString().Trim();
            if (dr.Table.Columns.Contains("AreaID"))
            {
                org.Area = new Area() { AreaID = dr["AreaID"].ToString().Trim() };
            }
            else
            {
                org.Area = new Area();
            }

            if (dr.Table.Columns.Contains("SNKEY"))
            {

                org.SNKEY = new HZ.Common.ConvertHelper(dr["SNKEY"]).String ?? "";
            }
            return org;
        }

        /// <summary>
        /// 根据DataTable获得Org对象集合
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static IList<Org> GetOrgsFromDataTable(DataTable dt)
        {
            IList<Org> orgs = new List<Org>(dt.Rows.Count);
            foreach (DataRow dr in dt.Rows)
            {
                orgs.Add(GetOrgFromDataRow(dr));
            }
            return orgs;
        }
        #endregion

        #region Goods
        ///// <summary>
        ///// 根据DataRow获得Merchandise对象
        ///// </summary>
        ///// <param name="dr"></param>
        ///// <returns></returns>
        //public static Goods GetGoodsFromDataRow(DataRow dr)
        //{
        //    // 产品分类
        //    Sort pc = new Sort()
        //    {
        //        SortID = dr["SortID"].ToString(),
        //        SortName = new HZ.Common.ConvertHelper(dr["SortName"]).String,
        //        ParentSortID = new HZ.Common.ConvertHelper(dr["ParentSortID"]).String
        //    };
        //    // 产品
        //    Product product = new Product()
        //    {
        //        MedicineModel = pharmacytype,
        //        ProductName = dr["ProductName"].ToString(),
        //        ProductID = dr["ProductID"].ToString(),
        //        Outlookc = dr["Outlookc"].ToString(),
        //        Unit = dr["Unit"].ToString(),
        //        Sort = pc
        //    };
        //    // 生产企业
        //    Company company_sc = new Company()
        //    {
        //        CompanyID = dr["CompanyID_SC"].ToString(),
        //        CompanyName_PS = dr["CompanyName_TB"].ToString(),
        //        // CompanyType = (EnumCompanyType)(int)dr["CompanyType"]
        //    };

        //    // 投标企业
        //    Company company_tb = new Company()
        //    {
        //        CompanyID = dr["CompanyID_TB"].ToString(),
        //        CompanyName_PS = dr["CompanyName_TB"].ToString()
        //    };
        //    // 商品
        //    Goods goods = new Goods()
        //    {
        //        Company_SC = company_sc,
        //        Company_TB = company_tb,
        //        Factor = new HZ.Common.ConvertHelper(dr["Factor"]).ToInt32 ?? 0,
        //        GoodsID = dr["GoodsID"].ToString(),
        //        GoodsName = dr["GoodsName"].ToString(),
        //        Pack = dr["Pack"].ToString(),
        //        Product = product
        //    };
        //    return goods;
        //}
        ///// <summary>
        ///// 返回产品信息实体(嵌套式)
        ///// </summary>
        ///// <param name="dt"></param>
        ///// <returns></returns>
        //public static IList<Goods> GetGoodsFromDataTable(DataTable dt)
        //{
        //    IList<Goods> Merchandises = new List<Goods>(dt.Rows.Count);
        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        Merchandises.Add(GetGoodsFromDataRow(dr));
        //    }
        //    return Merchandises;
        //}
        ///// <summary>
        ///// 将产品信息行转换为实体
        ///// </summary>
        ///// <param name="dr">DataRow</param>
        ///// <returns>产品信息</returns>
        //public static HZ.DrugTrade.Model.Query.Goods GetQueryGoodsFromDataRow(DataRow dr)
        //{
        //    Goods mec = GetGoodsFromDataRow(dr);
        //    HZ.DrugTrade.Model.Query.Goods qmedicine = new HZ.DrugTrade.Model.Query.Goods()
        //    {
        //        GoodsID = mec.GoodsID,
        //        GoodsName = mec.GoodsName,
        //        Pack = mec.Pack,
        //        Facotr = mec.Factor,
        //        ProductID = mec.Product.ProductID,
        //        Outlookc = mec.Product.Outlookc,
        //        Unit = mec.Product.Unit,
        //        CompanyID_SC = mec.Company_SC.CompanyID,
        //        CompanyName_SC = mec.Company_SC.CompanyName_PS,
        //        CompanyID_TB = mec.Company_TB.CompanyID,
        //        CompanyName_TB = mec.Company_TB.CompanyName_PS,
        //        SortID = mec.Product.Sort.SortID,
        //        SortName = mec.Product.Sort.SortName,
        //        ParentSortID = mec.Product.Sort.ParentSortID
        //    };
        //    return qmedicine;
        //}

        ///// <summary>
        ///// 获取查询产品信息
        ///// </summary>
        ///// <param name="dt">DataTable</param>
        ///// <returns>产品信息列表</returns>
        //public static IList<HZ.DrugTrade.Model.Query.Goods> GetQueryGoodsFromDataTable(DataTable dt)
        //{
        //    IList<HZ.DrugTrade.Model.Query.Goods> lstMerchandise = new List<HZ.DrugTrade.Model.Query.Goods>(dt.Rows.Count);
        //    foreach (DataRow item in dt.Rows)
        //    {
        //        lstMerchandise.Add(GetQueryGoodsFromDataRow(item));
        //    }
        //    return lstMerchandise;
        //}
        #endregion

        #region ProcureCatalog
        /// <summary>
        /// 获取采购目录单条数据
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static HZ.DrugTrade.Model.Query.ProcureCatalog GetQueryProcureCatalogFromDataRow(DataRow dr)
        {
            HZ.DrugTrade.Model.Query.ProcureCatalog mol_pc = new HZ.DrugTrade.Model.Query.ProcureCatalog()
            {
                GoodsID = new HZ.Common.ConvertHelper(dr["GoodsID"]).String,
                Outlookc = new HZ.Common.ConvertHelper(dr["Outlookc"]).String,
                Unit = new HZ.Common.ConvertHelper(dr["Unit"]).String,
                Factor = new HZ.Common.ConvertHelper(dr["Factor"]).ToInt32 ?? 0,
                Pack = new HZ.Common.ConvertHelper(dr["Pack"]).String,
                PackUnit = new HZ.Common.ConvertHelper(dr["PackUnit"]).String,
                GoodsName = new HZ.Common.ConvertHelper(dr["GoodsName"]).String,
                SortName = new HZ.Common.ConvertHelper(dr["SortName"]).String,
                CompanyName_SC = new HZ.Common.ConvertHelper(dr["CompanyName_SC"]).String,
                ProductID = new HZ.Common.ConvertHelper(dr["ProductID"]).String,
                SortID = new HZ.Common.ConvertHelper(dr["SortID"]).String,
                CompanyID_SC = new HZ.Common.ConvertHelper(dr["CompanyID_SC"]).String,
                ParentSortID = new HZ.Common.ConvertHelper(dr["FatherCategoryID"]).String,
                CompanyName_TB = new HZ.Common.ConvertHelper(dr["CompanyName_TB"]).String,
                CompanyID_TB = new HZ.Common.ConvertHelper(dr["CompanyID_TB"]).String,
                ProcureCatalogID = new HZ.Common.ConvertHelper(dr["ProcureCatalogID"]).String,
                ProcurePrice = new HZ.Common.ConvertHelper(dr["ProcurePrice"]).ToDouble,
                IsUsing = new HZ.Common.ConvertHelper(dr["IsUsing"]).ToBool ?? false,
                IsFlowing = new HZ.Common.ConvertHelper(dr["IsFlowing"]).ToBool ?? false,
                SortSource = new HZ.Common.ConvertHelper(dr["SortSource"]).String,
                AddTime = new HZ.Common.ConvertHelper(dr["AddTime"]).ToDateTime,
                CompanyIDs_PS = new HZ.Common.ConvertHelper(dr["CompanyIDs_PS"]).String,
                CompanyNames_PS = new HZ.Common.ConvertHelper(dr["CompanyNames_PS"]).String,
                ProjectID = new HZ.Common.ConvertHelper(dr["ProjectID"]).String,
                ProjectName = new HZ.Common.ConvertHelper(dr["ProjectName"]).String,
                ProcureStartTime = new HZ.Common.ConvertHelper(dr["ProcureStartTime"]).ToDateTime,
                ProcureEndTime = new HZ.Common.ConvertHelper(dr["ProcureEndTime"]).ToDateTime

            };
            return mol_pc;
        }
        /// <summary>
        /// 获取采购目录表列表
        /// </summary>
        /// <param name="dt"></param>
        /// <returns>采购目录表列表</returns>
        public static IList<HZ.DrugTrade.Model.Query.ProcureCatalog> GetQueryProcureCatalogFromDataTable(DataTable dt)
        {
            IList<HZ.DrugTrade.Model.Query.ProcureCatalog> lstProcureCatalog = new List<HZ.DrugTrade.Model.Query.ProcureCatalog>(dt.Rows.Count);
            foreach (DataRow item in dt.Rows)
            {
                lstProcureCatalog.Add(GetQueryProcureCatalogFromDataRow(item));
            }
            return lstProcureCatalog;
        }
        #endregion

        #region ProcurementProject

        public static ProcurementProject GetProcurementProjectFromDataRow(DataRow dr)
        {
            ProcurementProject pp = new ProcurementProject()
            {
                ProjectID = new HZ.Common.ConvertHelper(dr["ProjectID"]).String,
                ProjectName = new HZ.Common.ConvertHelper(dr["ProjectName"]).String,
                ProcureStartTime = new HZ.Common.ConvertHelper(dr["ProcureStartTime"]).ToDateTime.Value,
                ProcureEndTime = new HZ.Common.ConvertHelper(dr["ProcureEndTime"]).ToDateTime.Value
            };
            return pp;

        }

        public static IList<ProcurementProject> GetProcurementProjectFromDataTable(DataTable dt)
        {

            IList<ProcurementProject> list = new List<ProcurementProject>(dt.Rows.Count);
            foreach (DataRow item in dt.Rows)
            {
                list.Add(GetProcurementProjectFromDataRow(item));
            }
            return list;
        }
        #endregion

        #region Company
        /// <summary>
        /// 根据DataRow获得Company对象
        /// </summary>
        /// <param name="dr">DataRow</param>
        /// <returns></returns>
        public static Company GetCompanyFromDataRow(DataRow dr)
        {
            Company model = new Company();
            model.CompanyID = dr["CompanyID"].ToString().Trim();
            model.CompanyName = dr["CompanyName"].ToString().Trim();
            model.CompanyType = EnumParse.GetCompanyType(dr["CompanyType"].ToString().Trim());
            model.SNKEY = dr["SNKEY"].ToString().Trim();

            return model;
        }

        /// <summary>
        /// 根据DataTable获得Company对象集合
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static IList<Company> GetCompaniesFromDataTable(DataTable dt)
        {
            IList<Company> list = new List<Company>(dt.Rows.Count);
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(GetCompanyFromDataRow(dr));
            }
            return list;
        }


        #endregion

        #region Hospital


        /// <summary>
        /// 根据DataRow获得Hospital对象
        /// </summary>
        /// <param name="dr">DataRow</param>
        /// <returns></returns>
        public static Hospital GetHospitalFromDataRow(DataRow dr)
        {
            Hospital model = new Hospital();
            model.HospitalID = dr["HospitalID"].ToString().Trim();
            model.HospitalName = dr["HospitalName"].ToString().Trim();
            model.Area = new Area
            {
                AreaID = (dr["AreaID"] == null) ? "" : dr["AreaID"].ToString().Trim(),
                //AreaName = (dr["AreaName"] == null) ? "" : dr["AreaName"].ToString().Trim(),
                //FatherAreaID = (dr["FatherAreaID"] == null) ? "" : dr["FatherAreaID"].ToString().Trim()
            };
            //新增加是否启用
            model.IsUsing = Convert.ToInt32(dr["IsUsing"]);
            model.ContactPerson = dr["ContactPerson"].ToString().Trim();

            model.ContactTel = dr["ContactTel"].ToString().Trim();
            model.HospitalAddress = dr["HospitalAddress"].ToString().Trim();

            return model;
        }

        /// <summary>
        /// 根据DataTable获得Hospital对象集合
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static IList<Hospital> GetHospitalsFromDataTable(DataTable dt)
        {
            IList<Hospital> list = new List<Hospital>(dt.Rows.Count);
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(GetHospitalFromDataRow(dr));
            }
            return list;
        }

        #endregion

        #region GenericOperator

        #region 根据数据行构造泛型实体
        /// <summary>
        /// 根据数据行构造泛型实体
        /// </summary>
        /// <typeparam name="T">返回的实体类型</typeparam>
        /// <param name="dr">数据行</param>
        /// <returns></returns>
        public static T CommonFill<T>(DataRow dr) where T : new()
        {
            //构造泛型实体
            T result = new T();

            //获得泛型类型
            Type t = typeof(T);

            //属性集合
            PropertyInfo[] properties = t.GetProperties();

            //属性赋值
            foreach (var item in properties)
            {
                if (!dr.Table.Columns.Contains(item.Name))
                {
                    continue;
                }

                //字符串
                if (item.PropertyType == typeof(string))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(dr[item.Name]).String, null);
                }

                //整数（不可空）
                if (item.PropertyType == typeof(int))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(dr[item.Name]).ToInt32 ?? 0, null);
                }

                //整数（可空）
                if (item.PropertyType == typeof(int?))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(dr[item.Name]).ToInt32, null);
                }

                //布尔（不可空）
                if (item.PropertyType == typeof(bool))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(dr[item.Name]).ToBool ?? false, null);
                }

                //布尔（可空）
                if (item.PropertyType == typeof(bool?))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(dr[item.Name]).ToBool, null);
                }

                //时间（不可空）
                if (item.PropertyType == typeof(DateTime))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(dr[item.Name]).ToDateTime.GetValueOrDefault(DateTime.Now), null);
                }

                //时间（可空）
                if (item.PropertyType == typeof(DateTime?))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(dr[item.Name]).ToDateTime, null);
                }

                //实数（不可空）
                if (item.PropertyType == typeof(double))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(dr[item.Name]).ToDouble.Value, null);
                }

                //实数（可空）
                if (item.PropertyType == typeof(double?))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(dr[item.Name]).ToDouble, null);
                }

                //十进制实数（不可空）
                if (item.PropertyType == typeof(decimal))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(dr[item.Name]).ToDecimal.Value, null);
                }

                //十进制实数（可空）
                if (item.PropertyType == typeof(decimal?))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(dr[item.Name]).ToDecimal, null);
                }

            }

            return result;
        }
        #endregion

        #region 根据数据表构造泛型集合
        /// <summary>
        /// 根据数据表构造泛型集合
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="dt">数据表</param>
        /// <returns>泛型实体集合</returns>
        public static IList<T> CommonFillList<T>(DataTable dt) where T : new()
        {
            //泛型集合
            IList<T> list = new List<T>(dt.Rows.Count);

            //循环插入
            foreach (DataRow item in dt.Rows)
            {
                list.Add(CommonFill<T>(item));
            }
            return list;
        }
        #endregion

        #region 由泛型实体构造查询字符串
        /// <summary>
        /// 由泛型实体构造查询字符串
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="t">泛型实体Model对象</param>
        /// <returns>查询条件字符串</returns>
        public static string GetWhereCondition<T>(T t)
        {
            //构造查询条件
            StringBuilder where = new StringBuilder(512);
            Type type = typeof(T);
           
            if (t == null)
                return string.Empty;
            PropertyInfo sortproperty = null;
            string defaultorderby = string.Empty;
          

            foreach (PropertyInfo item in type.GetProperties())
            {
                if (string.IsNullOrEmpty(defaultorderby))
                {
                    if (item.Name.ToLower() != "sortfields" && item.Name.ToLower() != "append")
                    {
                        defaultorderby = item.Name;
                    }
                }
               

                //字段为空不拼接入查询条件
                if (item.GetValue(t, null) == null)
                    continue;

                //字符串类型
                if (item.PropertyType == typeof(string))
                {
                    if (item.Name.ToLower() == "pinyincode") //拼音码字段模糊查询
                    {
                        where.AppendFormat(" AND UPPER({0}) LIKE '%'||UPPER('{1}')||'%'", item.Name, item.GetValue(t, null).ToString().Trim());
                        continue;
                    }                   
                    //排序字段相关
                    if (item.Name.ToLower() == "sortfields")
                    {
                        sortproperty = item;
                        continue;
                    }
                    if (item.Name.ToLower() == "append")
                    {
                        where.AppendFormat(" AND ({0})", item.GetValue(t, null));
                        continue;
                    }
                    //地区字段模糊查询 add by ligang 2009-05-18
                    if (item.Name.ToLower() == "areaid")
                    {
                        where.AppendFormat(" AND {0} LIKE '{1}%'", item.Name, HZ.Common.MyString.TrimEnd( item.GetValue(t, null).ToString(),"00"));
                        continue;
                    }
                   
                    if (item.GetValue(t, null).ToString() == string.Empty)
                    {
                        continue;
                    }

                    //主键字段精确查询
                    if (item.Name.ToLower().Contains("id"))
                    {
                        where.AppendFormat(" AND {0} = '{1}'", item.Name, item.GetValue(t, null).ToString().Replace("'",""));
                    }
                    else
                    {
                        where.AppendFormat(" AND {0} LIKE '%{1}%'", item.Name, item.GetValue(t, null).ToString().Replace("'", ""));
                    }
                }
                //实数类型
                if (item.PropertyType == typeof(double?))
                {
                    //如果以“to结尾的是小于等于这个数”
                    if (item.Name.ToLower().EndsWith("to"))
                    {
                        where.AppendFormat(" AND {0} <= {1}", item.Name.Replace("To", ""), item.GetValue(t, null));
                    }
                    //如果以“from结尾的是大于于等于这个数”
                    else if (item.Name.ToLower().EndsWith("from"))
                    {
                        where.AppendFormat(" AND {0} >= {1}", item.Name.Replace("From", ""), item.GetValue(t, null));
                    }
                    else//等于
                    {
                        where.AppendFormat(" AND {0} = {1}", item.Name, item.GetValue(t, null));
                    }

                }
                //实数类型
                if (item.PropertyType == typeof(decimal?))
                {
                    //如果以“to结尾的是小于等于这个数”
                    if (item.Name.ToLower().EndsWith("to"))
                    {
                        where.AppendFormat(" AND {0} <= {1}", item.Name.Substring(0, item.Name.Length - 2), item.GetValue(t, null));
                    }
                    //如果以“from结尾的是大于于等于这个数”
                    else if (item.Name.ToLower().EndsWith("from"))
                    {
                        where.AppendFormat(" AND {0} >= {1}", item.Name.Substring(0, item.Name.Length - 4), item.GetValue(t, null));
                    }
                    else//等于
                    {
                        where.AppendFormat(" AND {0} = {1}", item.Name, item.GetValue(t, null));
                    }

                }
                //整数类型
                if (item.PropertyType == typeof(int?))
                {
                    //如果以“to结尾的是小于等于这个数”
                    if (item.Name.ToLower().EndsWith("to"))
                    {
                        where.AppendFormat(" AND {0} <= {1}", item.Name.Substring(0, item.Name.Length - 2), item.GetValue(t, null));
                    }
                    //如果以“from结尾的是大于于等于这个数”
                    else if (item.Name.ToLower().EndsWith("from"))
                    {
                        where.AppendFormat(" AND {0} >= {1}", item.Name.Replace("From", ""), item.GetValue(t, null));
                    }
                    else//等于
                    {
                        where.AppendFormat(" AND {0} = {1}", item.Name, item.GetValue(t, null));
                    }

                }
                //日期类型
                if (item.PropertyType == typeof(DateTime?))
                {
                    //如果以“to结尾的是晚于等于这个日期”
                    if (item.Name.ToLower().EndsWith("to"))
                    {
                        where.AppendFormat(" AND {0} <= '{1}'", item.Name.Substring(0, item.Name.Length - 2), ((DateTime?)item.GetValue(t, null)).Value.ToShortDateString());
                    }
                    //如果以“from结尾的是早于等于日期”
                    else if (item.Name.ToLower().EndsWith("from"))
                    {
                        where.AppendFormat(" AND {0} >= '{1}'", item.Name.Substring(0, item.Name.Length - 4), ((DateTime?)item.GetValue(t, null)).Value.ToShortDateString());
                    }
                    else//等于
                    {
                        where.AppendFormat(" AND {0} = '{1}'", item.Name, ((DateTime?)item.GetValue(t, null)).Value.ToShortDateString());
                    }

                }
                //逻辑类型
                if (item.PropertyType == typeof(bool?))
                {
                    where.AppendFormat(" AND {0} = {1}", item.Name, (((bool?)item.GetValue(t, null)).Value ? 1 : 0));
                }


            }

            // HZ.Common.ThrowHelper.Throw(sortproperty != null, "该实体类没有SortFields属性");

            string orderby = string.Empty;

            // = sortproperty.GetValue(t, null).ToString();
            // HZ.Common.ThrowHelper.Throw(!string.IsNullOrEmpty(orderby), "SortFields未经赋值请将排序字段赋值。");
            // HZ.Common.ThrowHelper.Throw(!orderby.ToLower().Contains("order by"), "排序字段不应该包含order by");
            if (sortproperty == null || string.IsNullOrEmpty(sortproperty.GetValue(t, null).ToString()))
            {
                orderby = defaultorderby;
                //PKCache
            }
            else
            {
                orderby = sortproperty.GetValue(t, null).ToString();
            }

            
            where.AppendFormat(" ORDER BY {0}", orderby);
            return where.ToString();
        }

        /// 由泛型实体构造查询字符串
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="t">泛型实体Model对象</param>
        /// <returns>查询条件字符串</returns>
        public static string GetWhereCondition<T>(T t, bool usesorderby)
        {
            //构造查询条件
            StringBuilder where = new StringBuilder(512);
            Type type = typeof(T);
            if (t == null)
                return string.Empty;
            PropertyInfo sortproperty = null;
            string defaultorderby = string.Empty;
            foreach (PropertyInfo item in type.GetProperties())
            {
                if (string.IsNullOrEmpty(defaultorderby))
                {
                    if (item.Name.ToLower() != "sortfields" && item.Name.ToLower() != "append")
                    {
                        defaultorderby = item.Name;
                    }
                }
                //字段为空不拼接入查询条件
                if (item.GetValue(t, null) == null)
                    continue;

                //字符串类型
                if (item.PropertyType == typeof(string))
                {
                    //if (item.Name.ToLower() == "pinyincode") //拼音码字段模糊查询
                    //{
                    //    where.AppendFormat(" AND UPPER({0}) LIKE '%'||UPPER('{1}')||'%'", item.Name, item.GetValue(t, null).ToString().Trim());
                    //    continue;
                    //}
                    //排序字段相关
                    if (item.Name.ToLower() == "sortfields")
                    {
                        sortproperty = item;
                        continue;
                    }
                    if (item.Name.ToLower() == "append")
                    {
                        where.AppendFormat(" AND ({0})", item.GetValue(t, null));
                        continue;
                    }
                    //地区字段模糊查询 add by ligang 2009-05-18
                    if (item.Name.ToLower() == "areaid")
                    {
                        where.AppendFormat(" AND {0} LIKE '{1}%'", item.Name, HZ.Common.MyString.TrimEnd(item.GetValue(t, null).ToString(), "00"));
                        continue;
                    }

                    if (item.GetValue(t, null).ToString() == string.Empty)
                    {
                        continue;
                    }

                    //主键字段精确查询
                    if (item.Name.ToLower().Contains("id"))
                    {
                        where.AppendFormat(" AND {0} = '{1}'", item.Name, item.GetValue(t, null).ToString().Replace("'", ""));
                    }
                    else
                    {
                        where.AppendFormat(" AND {0} LIKE '%{1}%'", item.Name, item.GetValue(t, null).ToString().Replace("'", ""));
                    }
                }
                //实数类型
                if (item.PropertyType == typeof(double?))
                {
                    //如果以“to结尾的是小于等于这个数”
                    if (item.Name.ToLower().EndsWith("to"))
                    {
                        where.AppendFormat(" AND {0} <= {1}", item.Name.Replace("To", ""), item.GetValue(t, null));
                    }
                    //如果以“from结尾的是大于于等于这个数”
                    else if (item.Name.ToLower().EndsWith("from"))
                    {
                        where.AppendFormat(" AND {0} >= {1}", item.Name.Replace("From", ""), item.GetValue(t, null));
                    }
                    else//等于
                    {
                        where.AppendFormat(" AND {0} = {1}", item.Name, item.GetValue(t, null));
                    }

                }
                //实数类型
                if (item.PropertyType == typeof(decimal?))
                {
                    //如果以“to结尾的是小于等于这个数”
                    if (item.Name.ToLower().EndsWith("to"))
                    {
                        where.AppendFormat(" AND {0} <= {1}", item.Name.Substring(0, item.Name.Length - 2), item.GetValue(t, null));
                    }
                    //如果以“from结尾的是大于于等于这个数”
                    else if (item.Name.ToLower().EndsWith("from"))
                    {
                        where.AppendFormat(" AND {0} >= {1}", item.Name.Substring(0, item.Name.Length - 4), item.GetValue(t, null));
                    }
                    else//等于
                    {
                        where.AppendFormat(" AND {0} = {1}", item.Name, item.GetValue(t, null));
                    }

                }
                //整数类型
                if (item.PropertyType == typeof(int?))
                {
                    //如果以“to结尾的是小于等于这个数”
                    if (item.Name.ToLower().EndsWith("to"))
                    {
                        where.AppendFormat(" AND {0} <= {1}", item.Name.Substring(0, item.Name.Length - 2), item.GetValue(t, null));
                    }
                    //如果以“from结尾的是大于于等于这个数”
                    else if (item.Name.ToLower().EndsWith("from"))
                    {
                        where.AppendFormat(" AND {0} >= {1}", item.Name.Replace("From", ""), item.GetValue(t, null));
                    }
                    else//等于
                    {
                        where.AppendFormat(" AND {0} = {1}", item.Name, item.GetValue(t, null));
                    }

                }
                //日期类型
                if (item.PropertyType == typeof(DateTime?))
                {
                    //如果以“to结尾的是晚于等于这个日期”
                    if (item.Name.ToLower().EndsWith("to"))
                    {
                        where.AppendFormat(" AND {0} <= to_date('{1}' ,'yyyy-mm-dd hh24:Mi:ss')", item.Name.Substring(0, item.Name.Length - 2), ((DateTime?)item.GetValue(t, null)).Value.ToShortDateString());
                    }
                    //如果以“from结尾的是早于等于日期”
                    else if (item.Name.ToLower().EndsWith("from"))
                    {
                        where.AppendFormat(" AND {0} >= to_date('{1}' ,'yyyy-mm-dd hh24:Mi:ss')", item.Name.Substring(0, item.Name.Length - 4), ((DateTime?)item.GetValue(t, null)).Value.ToShortDateString());
                    }
                    else//等于
                    {
                        where.AppendFormat(" AND {0} = to_date('{1}' ,'yyyy-mm-dd hh24:Mi:ss')", item.Name, ((DateTime?)item.GetValue(t, null)).Value.ToShortDateString());
                    }

                }
                //逻辑类型
                if (item.PropertyType == typeof(bool?))
                {
                    where.AppendFormat(" AND {0} = {1}", item.Name, (((bool?)item.GetValue(t, null)).Value ? 1 : 0));
                }


            }

            // HZ.Common.ThrowHelper.Throw(sortproperty != null, "该实体类没有SortFields属性");

            if (usesorderby)
            {
                string orderby = string.Empty;

                // = sortproperty.GetValue(t, null).ToString();
                // HZ.Common.ThrowHelper.Throw(!string.IsNullOrEmpty(orderby), "SortFields未经赋值请将排序字段赋值。");
                // HZ.Common.ThrowHelper.Throw(!orderby.ToLower().Contains("order by"), "排序字段不应该包含order by");
                if (sortproperty == null || string.IsNullOrEmpty(sortproperty.GetValue(t, null).ToString()))
                {
                    orderby = defaultorderby;
                    //PKCache
                }
                else
                {
                    orderby = sortproperty.GetValue(t, null).ToString();
                }
                where.AppendFormat(" ORDER BY {0}", orderby);
            }
            
            return where.ToString();
        }
        #endregion

        #region 根据泛型实体获取参数集合
        /// <summary>
        /// 根据泛型实体获取参数集合
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="t">泛型实体</param>
        /// <returns>参数集合</returns>
        public static IDataParameter[] GetDataParameter<T>(T t)
        {

            Type type = typeof(T);
            PropertyInfo[] Properties = type.GetProperties();

            IDataParameter[] paras = new IDataParameter[Properties.Length + 1];
            for (int i = 0; i < Properties.Length; i++)
            {
                paras[i] = new SqlParameter(string.Format("@in_{0}", Properties[i].Name), Properties[i].GetValue(t, null));
            }

            paras[Properties.Length] = new SqlParameter("@out_success", SqlDbType.Int);
            paras[Properties.Length].Direction = ParameterDirection.Output;
            return paras;
        }
        #endregion

        #region 构造并执行一般数据操作【单表增改】存储过程（默认返回值：0.操作失败;1.操作成功）
        /// <summary>
        /// 构造并执行一般数据操作【单表增改】存储过程（默认返回值：0.操作失败;1.操作成功）
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="t">泛型实体</param>
        /// <param name="tboperator">表操作枚举</param>
        /// <returns>（默认返回值：0.操作失败;1.操作成功）</returns>
        public static int OperateTable<T>(T t, TableOperator tboperator)
        {
            //构造参数列表
            IDataParameter[] paras = HZ.Data.DAL_Helper.GetDataParameter<T>(t);

            //获得泛型的类型
            Type type = typeof(T);
            string tablename = type.Name;
            string ProcedureName = string.Format("usp_{0}_{1}", tablename, tboperator.ToString());

            HZ.Data.DbHelperFactory.Create().ExecuteNonQuery(CommandType.StoredProcedure, ProcedureName, paras);
            return (int)paras[paras.Length - 1].Value;
        }
        /// <summary>
        /// 执行表操作增加 删除 修改 (空值忽略)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="tboperator"></param>
        /// <returns></returns>
        public static int OperateTableSQL<T>(T t, TableOperator tboperator)
        {
            string sql = string.Empty;
            switch (tboperator)
            {
                case TableOperator.Add:
                    sql = GetInsertSql(t);
                    break;
                case TableOperator.Update:
                    sql = GetUpdateSql(t);
                    break;
                case TableOperator.Delete:
                    sql = GetDeleteSql(t);
                    break;
                default:
                    throw new NotSupportedException("不支持的表操作");
            }
            return HZ.Data.DbHelperFactory.Create().ExecuteNonQuery(sql);
        }
        #endregion

        #region 根据主键获取实体类
        /// <summary>
        /// 根据主键获取实体类
        /// </summary>
        /// <typeparam name="T">实体类类型</typeparam>
        /// <param name="t">实体类实体</param>
        /// <returns>Fill完的实体类</returns>
        public static T GetModelByID<T>(T t) where T : new()
        {
            //获得泛型的类型
            Type type = t.GetType();

            //构造表名（我们已经约定：TB_ClassName为表名）
            string TableName = string.Format("TB_{0}", type.Name);

            //缓存主键字段
            IList<string> pkfields = PKCache[TableName];

            //构造属性字典
            IDictionary<string, PropertyInfo> pkproperties = new Dictionary<string, PropertyInfo>();
            foreach (var item in type.GetProperties())
                pkproperties.Add(item.Name, item);

            // 拼装主键参数
            SqlParameter[] paras = new SqlParameter[pkfields.Count];
            for (int i = 0; i < pkfields.Count; i++)
                paras[i] = new SqlParameter(string.Format("@{0}", pkfields[i]), pkproperties[pkfields[i]].GetValue(t, null));

            // 拼装SQL
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat("SELECT TOP 1 * FROM {0} WHERE 1=1", TableName);

            for (int i = 0; i < pkfields.Count; i++)
            {
                sql.AppendFormat(" AND {0} = @{0}", pkfields[i]);
            }

            //执行查询返回数据表
            DataTable dt = HZ.Data.DbHelperFactory.Create().ExecuteTable(CommandType.Text, sql.ToString(), paras);

            HZ.Common.ThrowHelper.Throw(dt.Rows.Count == 1, "没有找到改条数据，请检查主键。");
            //用数据表填充泛型实体并返回
            return CommonFill<T>(dt.Rows[0]);
        }
        #endregion

        #region 刷新主键缓存
        /// <summary>
        /// 刷新主键缓存
        /// </summary>
        private static void RefreshPKCache()
        {
            _PKCache = new Dictionary<string, IList<string>>(64);
            DataTable dt = HZ.Data.DbHelperFactory.Create().ExecuteTable(@"SELECT * FROM (
SELECT  d.name  AS TableName, 
      a.colorder AS FieldPos, a.name AS FieldName, 
      CASE WHEN EXISTS
          (SELECT 1
         FROM sysindexes si INNER JOIN
               sysindexkeys sik ON si.id = sik.id AND si.indid = sik.indid INNER JOIN
               syscolumns sc ON sc.id = sik.id AND sc.colid = sik.colid INNER JOIN
               sysobjects so ON so.name = si.name AND so.xtype = 'PK'
         WHERE sc.id = a.id AND sc.colid = a.colid) THEN '1' ELSE '0' END AS PK
FROM syscolumns a LEFT OUTER JOIN
      systypes b ON a.xtype = b.xusertype INNER JOIN
      sysobjects d ON a.id = d.id AND d.xtype = 'U' AND 
      d.status >= 0 LEFT OUTER JOIN
      syscomments e ON a.cdefault = e.id LEFT OUTER JOIN
      sys.extended_properties g ON a.id = g.major_id AND a.colid = g.minor_id AND 
      g.name = 'MS_Description' LEFT OUTER JOIN
      sys.extended_properties f ON d.id = f.major_id AND f.minor_id = 0 AND 
      f.name = 'MS_Description'

) AS A
WHERE A.PK = '1'
ORDER BY A.[TableName], A.[FieldPos]");

            foreach (DataRow item in dt.Rows)
            {
                string TableName = item["TableName"].ToString();
                if (!_PKCache.Keys.Contains(TableName))
                {
                    IList<string> pkfields = new List<string>();
                    pkfields.Add(item["FieldName"].ToString());
                    PKCache[TableName] = pkfields;
                }
                else
                {
                    _PKCache[TableName].Add(item["FieldName"].ToString());
                }
            }
        }
        #endregion

        #region 分页查询视图
        /// <summary>
        /// 分页查询视图
        /// </summary>
        /// <typeparam name="V">视图类</typeparam>
        /// <typeparam name="Q">查询实体类</typeparam>
        /// <param name="where"></param>
        /// <param name="currentpage">当前页</param>
        /// <param name="pagesize">页大小</param>
        /// <param name="totalrecord">页数据总数</param>
        /// <returns>实体列表</returns>
        public static IList<V> GetPagedView<V, Q>(Q where, int currentpage, int pagesize, out int totalrecord) where V : new()
        {
            string condition = DAL_Helper.GetWhereCondition(where,true);

            HZ.Data.PageDescribe pdes = new HZ.Data.PageDescribe(string.Format("SELECT * FROM View_{1} WHERE 1=1 {0} ", condition, typeof(V).Name), pagesize);
            pdes.CurrentPage = currentpage;
            totalrecord = pdes.TotalCount;

            DataTable dt = pdes.GetSpecailPage();
            return DAL_Helper.CommonFillList<V>(dt);
        }
        #endregion

        #region 构造实体集合
        /// <summary>
        /// 构造实体集合
        /// </summary>
        /// <typeparam name="T">泛型类型</typeparam>
        /// <param name="sql">查询语句</param>
        /// <param name="paras">参数</param>
        /// <returns>实体集合</returns>
        public static IList<T> GetModelList<T>(string sql, SqlParameter[] paras) where T : new()
        {
            DataTable dt = HZ.Data.DbHelperFactory.Create().ExecuteTable(CommandType.Text, sql, paras);
            return DAL_Helper.CommonFillList<T>(dt);
        }
        #endregion

        #region 分隔字符串
        /// <summary>
        /// 将数组按指定内容进行分隔(aa,bb)
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="tlist">泛型集合</param>
        /// <param name="fieldname">字段名称</param>
        /// <param name="splitstring">分割符号</param>
        /// <returns>分隔好的字符串</returns>
        public static string GetModelFieldArrayString<T>(IList<T> tlist, string fieldname, string splitstring)
        {
            Type type = typeof(T);
            PropertyInfo property = type.GetProperty(fieldname);
            if (property == null)
            {
                throw new ArgumentException("fieldname", "");

            }
            StringBuilder result = new StringBuilder(512);
            for (int i = 0; i < tlist.Count; i++)
            {
                if (i == 0)
                {
                    result.Append(property.GetValue(tlist[i], null));
                }
                else
                {
                    result.AppendFormat("{0}{1}", splitstring, property.GetValue(tlist[i], null).ToString().Replace(splitstring, " "));
                }

            }
            return result.ToString();

        }

        /// <summary>
        /// 将数组按指定内容进行分隔(aa,bb)
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="tlist">泛型集合</param>
        /// <param name="fieldname">字段名称</param>
        /// <param name="splitstring">分割符号</param>
        /// <param name="usequot">使用引用</param>
        /// <returns>分隔好的字符串</returns>
        public static string GetModelFieldArrayString<T>(IList<T> tlist, string fieldname, string splitstring, bool usequot)
        {
            Type type = typeof(T);
            PropertyInfo property = type.GetProperty(fieldname);
            if (property == null)
            {
                throw new ArgumentException("fieldname", "");

            }

            if (!usequot || property.PropertyType != typeof(string))
            {
                StringBuilder result = new StringBuilder(512);
                for (int i = 0; i < tlist.Count; i++)
                {
                    if (i == 0)
                    {
                        result.Append(property.GetValue(tlist[i], null));
                    }
                    else
                    {
                        result.AppendFormat("{0}{1}", splitstring, property.GetValue(tlist[i], null).ToString().Replace(splitstring, " "));
                    }

                }
                return result.ToString();
            }
            else
            {
                StringBuilder result = new StringBuilder(512);
                for (int i = 0; i < tlist.Count; i++)
                {
                    if (i == 0)
                    {
                        result.AppendFormat("'{0}'", property.GetValue(tlist[i], null));
                    }
                    else
                    {
                        result.AppendFormat("{0}'{1}'", splitstring, property.GetValue(tlist[i], null).ToString().Replace(splitstring, " "));
                    }

                }
                return result.ToString();
            }


        }

        /// <summary>
        /// 将bool数组按指定内容进行分隔(0,1)
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="tlist">泛型集合</param>
        /// <param name="fieldname">字段名称</param>
        /// <param name="splitstring">分割符号</param>
        /// <returns>分隔好的字符串</returns>
        public static string GetModelFieldArrayBit<T>(IList<T> tlist, string fieldname, string splitstring)
        {
            string strTemp = GetModelFieldArrayString<T>(tlist, fieldname, splitstring);
            strTemp = strTemp.ToLower().Replace("false", "0");
            strTemp = strTemp.ToLower().Replace("true", "1");
            return strTemp;

        }
        private const string Table_Pre = "TB_";
        private const string View_Pre = "View_";
        /// <summary>
        /// 根据实体生成插入语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string GetInsertSql<T>(T t)
        {
            Type type = typeof(T);
            StringBuilder columns = new StringBuilder(64);
            StringBuilder values = new StringBuilder(64);
            columns.AppendFormat("INSERT INTO {0} (", Table_Pre + type.Name.Replace(TAIL, ""));
            PropertyInfo[] properties = type.GetProperties();
            bool first = true;
            for (int i = 0; i < properties.Length; i++)
            {
                object value = properties[i].GetValue(t, null);
                string valuestr;
                if (value == null)
                {
                    continue;
                }
                else
                    valuestr = string.Format("'{0}'", value.ToString().Replace("'", ""));

                if (first)
                {
                    values.Append(valuestr);

                    columns.Append(properties[i].Name);
                    first = false;
                }
                else
                {
                    values.AppendFormat(",{0}", valuestr);


                    columns.AppendFormat(",{0}", properties[i].Name);
                }
            }
            return string.Format("{0}) VALUES ({1})", columns.ToString(), values.ToString());

        }
        /// <summary>
        /// 生成更新查询语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string GetUpdateSql<T>(T t)
        {
            StringBuilder where = new StringBuilder("1=1");
            Type type = t.GetType();
            string TableName = Table_Pre + type.Name.Replace(TAIL, "");
            IList<string> Pkstr = PKCache[TableName];
            if (Pkstr == null || Pkstr.Count == 0)
            {
                throw new Exception("没有主键的表不能更新");
            }
            StringBuilder update = new StringBuilder();
            PropertyInfo[] properties = type.GetProperties();
            bool first = true;
            foreach (var item in properties)
            {
                object value = item.GetValue(t, null);
                if (value == null)
                {
                    continue;
                }
                if (Pkstr.Contains(item.Name))
                {
                    where.AppendFormat(" AND {0}='{1}'", item.Name, value.ToString().Replace("'", ""));

                }
                else
                {
                    if (first)
                    {

                        update.AppendFormat("{0}='{1}'", item.Name, value.ToString());
                        first = false;
                    }
                    else
                    {
                        update.AppendFormat(",{0}='{1}'", item.Name, value.ToString());
                    }
                }
            }
            if (update.Length == 0)
            {
                throw new ArgumentException("未发现需要更新字段");
            }

            return string.Format("UPDATE {0} SET {1} WHERE {2}", TableName, update.ToString(), where.ToString());
        }
        /// <summary>
        /// 生成删除语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string GetDeleteSql<T>(T t)
        {
            Type type = t.GetType();
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat("DELETE FROM {0} WHERE 1=1", Table_Pre + type.Name);
            PropertyInfo[] properties = type.GetProperties();
            StringBuilder where = new StringBuilder();

            IList<string> pkkeys = null;
            if (PKCache.Keys.Contains(Table_Pre + type.Name.Replace(TAIL, "").Replace("'", "")))
            {
                pkkeys = PKCache[Table_Pre + type.Name];
            }
            else
            {
                throw new Exception("没有主键的表不能删除");
            }
            foreach (var item in properties)
            {
                object value = item.GetValue(t, null);
                if (value == null)
                {
                    continue;
                }
                else
                {
                    if (pkkeys.Contains(item.Name))
                        where.AppendFormat(" AND {0} = '{1}'", item.Name, item.GetValue(t, null));
                }

            }
            if (where.Length == 0)
            {
                throw new ArgumentException("传入实体主键尚未赋值");
            }
            return sql.ToString() + where.ToString();
        }
        #endregion

        #region  获取泛型实体信息
        /// <summary>
        /// 获取泛型实体信息
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="t">泛型实体</param>
        /// <returns></returns>
        public static string GetModelInfo<T>(T t)
        {
            Type type = typeof(T);
            StringBuilder str = new StringBuilder(512);
            str.Append(string.Format("{0}:{{ ", type.Name));
            bool first = true;
            foreach (var item in type.GetProperties())
            {
                if (first)
                {

                    str.AppendFormat(@"{0}:{1}", item.Name, item.GetValue(t, null) ?? "NULL");
                    first = false;
                }
                else
                    str.AppendFormat(@", {0}:{1}", item.Name, item.GetValue(t, null) ?? "NULL");
            }
            str.Append(" }\r\n");
            return str.ToString();

        }



        #endregion

        #region 复制实体

        /// <summary>
        /// 复制实体
        /// </summary>
        /// <typeparam name="T">来源类型</typeparam>
        /// <typeparam name="V">返回类型</typeparam>
        /// <param name="t">来源类型的一个实例</param>
        /// <returns>待返回实体的实例</returns>
        public static V CopyModel<T, V>(T t) where V : new()
        {
            Type typet = typeof(T);
            Type typev = typeof(V);
            V v = new V();
            PropertyInfo[] properties = typev.GetProperties();
            foreach (var item in properties)
            {
                PropertyInfo tproperty = typet.GetProperty(item.Name);

                if (tproperty == null)
                {
                    continue;
                }
                if (tproperty.PropertyType != item.PropertyType)
                {
                    continue;
                }

                item.SetValue(v, tproperty.GetValue(t, null), null);
            }
            return v;
        }
        /// <summary>
        /// 复制实体列表
        /// </summary>
        /// <typeparam name="T">来源类型</typeparam>
        /// <typeparam name="V">返回类型</typeparam>
        /// <param name="tlist">来源类型列表</param>
        /// <returns>待返回实体的实例列表</returns>
        public static IList<V> CopyModelList<T, V>(IList<T> tlist) where V : new()
        {
            IList<V> list = new List<V>(tlist.Count);

            foreach (var item in tlist)
            {
                list.Add(CopyModel<T, V>(item));
            }
            return list;
        }

        #endregion

        #endregion

        #region 流程首节点缓存相关

        /// <summary>
        /// Lazy Load机制的流程首节点缓存。
        /// </summary>
        private static IDictionary<string, string> _FlowCache = null;
        /// <summary>
        /// 获取流程首节点缓存
        /// </summary>
        public static IDictionary<string, string> FlowCache
        {
            get
            {
                if (_FlowCache == null)
                {
                    IDataReader dr = HZ.Data.DbHelperFactory.Create().ExecuteReader("SELECT f.FlowID, n.NodeID FROM TB_Flow AS f INNER JOIN  TB_FlowNode AS n ON f.FlowID = n.FlowID WHERE n.FatherNodeID IS NULL ");
                    if (dr.Read())
                    {
                        _FlowCache = new Dictionary<string, string>(16);
                        do
                        {
                            _FlowCache[dr["FlowID"].ToString()] = dr["NodeID"].ToString();
                        }
                        while (dr.Read());
                    }
                    dr.Close();
                }
                return _FlowCache;
            }
            set
            {
                //清空首节点缓存
                _FlowCache = null;
            }

        }
        #endregion
    }

    #region 表操作枚举
    /// <summary>
    /// 表操作枚举
    /// </summary>
    public enum TableOperator
    {
        /// <summary>
        /// 新增
        /// </summary>
        Add,
        /// <summary>
        /// 更新
        /// </summary>
        Update,
        /// <summary>
        /// 删除
        /// </summary>
        Delete
    }
    #endregion
}
